package com.allqj.sfx.infrastructure;

import com.allqj.sfx.infrastructure.annotations.NotResultAdvice;
import com.allqj.sfx.infrastructure.utils.JsonUtil;
import com.allqj.sfx.infrastructure.vo.ResultVO;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author sjw
 * @className ResponseBodyAdviceHandler
 * @date 2022/7/19 9:52
 * @description: 返回值统一封装
 */

@ControllerAdvice(basePackages = "com.allqj.sfx")
public class ResponseBodyAdviceHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//        if(selectedConverterType == StringHttpMessageConverter.class)
        if (body instanceof ResultVO) return body;
        if (returnType.getMethod().getAnnotation(NotResultAdvice.class) == null && returnType.getMethod().getDeclaringClass().getAnnotation(NotResultAdvice.class) == null) {
            if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType))
                return JsonUtil.objectToJson(ResultVO.Instance(body));
            return ResultVO.Instance(body);
        } else {
            return body;
        }
    }
}
